package com.ruike.alisurface.ui.call;

import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.TextureView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.lgh.uvccamera.UVCCameraProxy;
import com.lgh.uvccamera.bean.PicturePath;
import com.lgh.uvccamera.callback.ConnectCallback;
import com.lgh.uvccamera.callback.PictureCallback;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.IdcardBean;
import com.ruike.alisurface.bean.MedicineBean;
import com.ruike.alisurface.https.ShopApiHttp;
import com.ruike.alisurface.serialport.MsgEventBus;
import com.ruike.alisurface.serialport.Ttys3Utils;
import com.ruike.alisurface.ui.ShopMain_Aty;
import com.ruike.alisurface.ui.adapters.CallProductAdapter;
import com.ruike.alisurface.ui.adapters.MedicationAdapter;
import com.ruike.alisurface.ui.adapters.PrescriptionAdapter;
import com.ruike.alisurface.ui.payPage.ShopPayType_Aty;
import com.ruike.alisurface.utils.BitmipUtil;
import com.ruike.alisurface.utils.CountTimeUtils;
import com.ruike.alisurface.utils.FinalDbUtils;
import com.ruike.alisurface.utils.GsonUtils;
import com.ruike.alisurface.utils.LinearItemDecoration;
import com.ruike.alisurface.utils.OrcIdUtil;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.FileUtils;
import com.voodoo.lib_utils.imageLoader.GlideImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;
import top.zibin.luban.OnRenameListener;

import static com.ruike.alisurface.https.ShopApiHttp.get_pay_info;

/**
 * 视频问诊页
 */
public class CallPrescription_Aty extends BaseCallActivity implements ApiListener {

    @BindView(R.id.call_product_rv)
    RecyclerView callProductRv;
    @BindView(R.id.call_main_line)
    View callMainLine;
    @BindView(R.id.call_main_line_range)
    LinearLayout callMainLineRange;
    @BindView(R.id.video_topay_tv)
    TextView videoTopayTv;
    @BindView(R.id.patient_idcard_name)
    TextView patientIdcardName;
    @BindView(R.id.patient_idcard_sex)
    TextView patientIdcardSex;
    @BindView(R.id.patient_idcard_people)
    TextView patientIdcardPeople;
    @BindView(R.id.patient_idcard_phone)
    TextView patientIdcardPhone;
    @BindView(R.id.patient_idcard_age)
    TextView patientIdcardAge;
    @BindView(R.id.patient_idcard_height)
    TextView patientIdcardHeight;
    @BindView(R.id.patient_idcard_number)
    TextView patientIdcardNumber;
    @BindView(R.id.video_prescription_lv)
    LinearLayout videoPrescriptionLv;
    @BindView(R.id.video_prescription_img_list)
    RecyclerView videoPrescriptionImgList;
    @BindView(R.id.call_doctor_content_ly)
    RelativeLayout callDoctorContentLy;
    @BindView(R.id.video_photo_prescription_tv)
    TextView videoPhotoPrescriptionTv;

    @BindView(R.id.prescription_takeidcard_tv)
    TextView prescriptionTakeidcardTv;
    @BindView(R.id.idcard_camare_lv)
    LinearLayout idcardCamareLv;
    @BindView(R.id.idcard_confirm_tv)
    TextView idcardConfirmTv;
    @BindView(R.id.idcard_calcal_tv)
    TextView idcardCalcalTv;
    @BindView(R.id.camare_idcard_layout)
    LinearLayout camareIdcardLayout;

    @BindView(R.id.call_give_up_the_purchase_tv)
    TextView callGiveUpThePurchaseTv;
    @BindView(R.id.take_prescription_ly)
    LinearLayout takePrescriptionLy;
    @BindView(R.id.prescription_diagnosis_tv)
    TextView prescriptionDiagnosisTv;
    @BindView(R.id.prescription_medication_rv)
    RecyclerView prescriptionMedicationRv;
    @BindView(R.id.text_prescription_ly)
    LinearLayout textPrescriptionLy;
    @BindView(R.id.time_out_tv)
    TextView time_out_tv;
    @BindView(R.id.call_doctor_wechat_img)
    ImageView call_doctor_wechat_img;
    @BindView(R.id.take_chufang_bt_ly)
    LinearLayout take_chufang_bt_ly;
    @BindView(R.id.call_success_times)
    TextView call_success_times;

    String order_id;//订单id
    String doctor_id;//  被呼叫的医生id
    int consultation_type = 1;//问诊类型  0 无处方  1 有处方  默认有处方

    int prescriptioncount = 0;//处方数量
    boolean isIdcard;//是否是身份证拍照

    CallProductAdapter mCallProductAdapter;//商品信息适配器
    List<MedicineBean.DataBean.OrderDetailsBean> mProductList = new ArrayList<>();//商品信息集合
    List<MedicineBean.DataBean.OrderDetailsBean> mShopPrescriptionList = new ArrayList<>();//商品处方信息集合


    PrescriptionAdapter mPrescriptionAdapter;//处方适配器

    List<String> mPrescriptionList = new ArrayList<>();//处方图片集合
    Handler mHandler = new Handler(Looper.getMainLooper());
    /**
     * 初始化UVC摄像头配置及操作
     */
    private UVCCameraProxy mUVCCamera;// 相机的控制
    String mProductId;//相机的id
    MedicineBean medicineBean;//问诊信息订单数据

    @Override
    protected int getLayoutResId() {
        return R.layout.app_call_prescription;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
        startTime(30, 0);

    }


    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            order_id = bundle.getString("order_id");
            consultation_type = bundle.getInt("consultation_type");
        }
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                initUVCCamera(12314);
            }
        });
        setSwitcPrescriptionly(consultation_type);
        setPrescriptionRv();
        setProductData();
        ShopApiHttp.get_medicine_order_details(order_id, this);
        checkOrder(0);

    }

    CountTimeUtils countTimeUtils;

    /**
     * 开始计时
     *
     * @param mStartTime
     * @param type
     */
    public void startTime(long mStartTime, int type) {
        mCancelTime();
        countTimeUtils = new CountTimeUtils(mStartTime) {
            @Override
            public void onTick(long mMillisUntilFinished) {
                time_out_tv.setText(String.format("%d s", mMillisUntilFinished));
            }

            @Override
            public void onFinish() {
                L.i("onFinish=", "时间到    ");
                cancelOrder();
                startActivity(ShopMain_Aty.class, null);
                finish();
            }
        };
        countTimeUtils.start();
    }

    /**
     * 取消计时
     */
    public void mCancelTime() {
        if (countTimeUtils != null) {
            countTimeUtils.cancel();
            countTimeUtils = null;
        }
    }

    Timer Ordertimer;
    TimerTask timerTask;

    /**
     * 查询问诊订单信息 是否接单
     */
    public void checkOrder(int type) {
        setCanal();
        Ordertimer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (type == 0) {
                    ShopApiHttp.query_order_sult_state(order_id, CallPrescription_Aty.this);
                } else {
                    ShopApiHttp.query_proc_order_state(order_id, CallPrescription_Aty.this);
                }
            }
        };
        Ordertimer.schedule(timerTask, 10, 3000);
    }


    public void setCanal() {
        if (timerTask != null) {
            L.i("==setCanal=取消计时=timerTask=" + timerTask);
            timerTask.cancel();
            timerTask = null;
        }
        if (Ordertimer != null) {
            L.i("==setCanal=取消计时=paytimer" + Ordertimer);
            Ordertimer.cancel();
            Ordertimer.purge();
            Ordertimer = null;
        }
    }

    public void getDoctorImg() {
        ShopApiHttp.get_doctor_code_pic_detail(doctor_id, CallPrescription_Aty.this);
    }

    public void cancelOrder() {
        ShopApiHttp.set_order_state_cancel(order_id, CallPrescription_Aty.this);
    }

    @OnClick({R.id.video_goback, R.id.video_photo_prescription_tv,
            R.id.video_confirm_send_tv, R.id.prescription_takeidcard_tv, R.id.idcard_confirm_tv,
            R.id.idcard_calcal_tv, R.id.video_topay_tv, R.id.call_give_up_the_purchase_tv

    })
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.video_goback:
            case R.id.call_give_up_the_purchase_tv:
                setCanal();
                mCancelTime();
                cancelOrder();
                startActivity(ShopMain_Aty.class, null);
                finish();
                break;
            case R.id.video_photo_prescription_tv:
                if (!isUsbCamera) {
                    showErrorToast("没有可用的USB相机");
                    return;
                }
                int imgLenght = 0;
                for (String path : mPrescriptionList) {
                    if (!path.equals("")) {
                        imgLenght++;
                    }
                }
                if (imgLenght >= 3) {
                    showRightToast("处方最多三张");
                    return;
                }
                isIdcard = false;
                showProgressDialog("拍照中，请等待...", false);
                mUVCCamera.takePicture("test.jpg");
                break;
            case R.id.video_confirm_send_tv:
                prescriptioncount = 0;
                for (String path : mPrescriptionList) {
                    if (!path.equals("")) {
                        prescriptioncount++;
                    }
                }
                if (prescriptioncount < 1) {
                    showErrorToast("请先拍照处方");
                    return;
                }

               /* if (urlpathList.size() > 0) {
                    showErrorToast("处方已经上传");
                    return;
                }*/
                urlpathList.clear();
                showProgressDialog("上传病例中，请等待...", false);
                for (String path : mPrescriptionList) {
                    if (!path.equals("")) {
                        File file = new File(path);
                        ShopApiHttp.get_medicine_upload(file, this);
                    }
                }

                break;
            case R.id.video_topay_tv:
                showProgressDialog("去支付方式中，请等待...", false);
                get_pay_info(order_id, this);
                break;
            case R.id.prescription_takeidcard_tv:
                if (!isIdcard) {
                    isIdcard = true;
                    camareIdcardLayout.setVisibility(View.VISIBLE);
                    videoPrescriptionLv.removeAllViews();
                    idcardCamareLv.addView(textureView);
                }
                break;
            case R.id.idcard_confirm_tv:
                if (!isUsbCamera) {
                    showErrorToast("没有可用的USB相机");
                    return;
                }
                showProgressDialog("拍照识别中，请等待...", false);
                mUVCCamera.takePicture("test.jpg");
                break;
            case R.id.idcard_calcal_tv:
                setSwitchmode();
                break;
        }
    }


    public void setPrescriptionRv() {
        mPrescriptionList.add("");
        mPrescriptionList.add("");
        mPrescriptionList.add("");
        mPrescriptionAdapter = new PrescriptionAdapter(mPrescriptionList, this);
        /**设置recyclerview*/
        LinearItemDecoration divider = new LinearItemDecoration.Builder(this)
                .setSpan(30f)
//                              .setPadding(R.dimen.line_width)
//                              .setLeftPadding(R.dimen.common_title_height)
//                              .setRightPadding(R.dimen.common_title_height)
                .setColorResource(R.color.color_white)
                .setShowLastLine(false)
                .build();
        videoPrescriptionImgList.addItemDecoration(divider);
        videoPrescriptionImgList.setLayoutManager(new LinearLayoutManager(this));
        videoPrescriptionImgList.setAdapter(mPrescriptionAdapter);

        mPrescriptionAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                L.i("Prescription", "点击了" + position);
                //判断id
                if (view.getId() == R.id.prescription_del) {
                    L.i("Prescription", "删除处方图片" + position);
                    delPrescriptionRv(position);
                }
            }
        });
    }

    int count = 0;

    public void upPrescriptionRv(String imgPath) {
        removeProgressDialog();
        if (mPrescriptionAdapter != null) {
            if (count > mPrescriptionList.size() - 1) {
                mPrescriptionList.add(imgPath);
                mPrescriptionAdapter.notifyDataSetChanged();
            } else {
                for (int i = 0; i < mPrescriptionList.size(); i++) {
                    if (mPrescriptionList.get(i).equals("")) {
                        mPrescriptionList.set(i, imgPath);
                        mPrescriptionAdapter.notifyItemChanged(i);
                        if (i == 2) {
                            count = i + 1;
                        } else {
                            count = i;
                        }
                        break;
                    }
                }
            }
        }
    }

    public void delPrescriptionRv(int position) {
        if (mPrescriptionAdapter != null) {
            if (mPrescriptionList.size() > 3) {
                mPrescriptionList.remove(position);
                mPrescriptionAdapter.notifyDataSetChanged();
                count = mPrescriptionList.size();
            } else {
                count = position;
                mPrescriptionList.set(position, "");
                mPrescriptionAdapter.notifyItemChanged(position);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Constant.isShopShipment = true;
        Ttys3Utils.getInstance().ledOpenOrClose(0, 1, true, 15, 15);


    }

    boolean isUsbCamera;
    TextureView textureView;

    private void initUVCCamera(int ProductId) {
        L.i("tjf-usb-", "开始初始化配置 == " + ProductId);
        textureView = new TextureView(this);
        videoPrescriptionLv.addView(textureView);
        mProductId = String.valueOf(ProductId);
        mUVCCamera = new UVCCameraProxy(this);
        // 已有默认配置，不需要可以不设置
        mUVCCamera.getConfig()
                .isDebug(true)
                .setPicturePath(PicturePath.SDCARD)
                .setDirName("/Images/")
                /* .setProductId(14371)
                 .setVendorId(1528);*/
                .setProductId(ProductId)
                .setVendorId(3034);//3034 //2760
//        mVendorId=3034,mProductId=12342  根据USB摄像头来区分 mVendorId供应商id   mProductId 产品id   ProductId(12936)  日期1020
        mUVCCamera.setPreviewTexture(textureView);
        mUVCCamera.setConnectCallback(new ConnectCallback() {
            @Override
            public void onAttached(UsbDevice usbDevice) {
                mUVCCamera.requestPermission(usbDevice);
                L.i("tjf-usb-", "请求连接 ");
            }

            @Override
            public void onGranted(UsbDevice usbDevice, boolean granted) {
                if (granted) {
                    mUVCCamera.connectDevice(usbDevice);
                    L.i("tjf-usb-", "连接 ");
                } else {
                    L.i("tjf-usb-", "请求连接 ");
                    mUVCCamera.requestPermission(usbDevice);
                }
            }

            @Override
            public void onConnected(UsbDevice usbDevice) {
                L.i("tjf-usb-", "打开 ");
                isUsbCamera = true;
                mUVCCamera.openCamera();
            }

            @Override
            public void onCameraOpened() {
                L.i("tjf-usb-", "打开成功并设置预览及开始");
//                showAllPreviewSizes();
                mUVCCamera.setPreviewSize(2592, 1944);
                mUVCCamera.startPreview();
            }

            @Override
            public void onDetached(UsbDevice usbDevice) {
                L.i("tjf-usb-", "关闭连接");
                isUsbCamera = false;
            }
        });

//        mUVCCamera.setPhotographCallback(new PhotographCallback() {
//            @Override
//            public void onPhotographClick() {
////                mUVCCamera.takePicture();
////                mUVCCamera.takePicture("test.jpg");
//            }
//        });
//
//        mUVCCamera.setPreviewCallback(new PreviewCallback() {
//            @Override
//            public void onPreviewFrame(byte[] yuv) {
//
//            }
//        });

        mUVCCamera.setPictureTakenCallback(new PictureCallback() {
            @Override
            public void onPictureTaken(final String path) {
                L.i("tjf-原图地址-" + path);
                lubanYasuo(path);
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        removeProgressDialog();

    }


    public void lubanYasuo(final String path) {
        FileUtils.checkFolderIsExists(isIdcard ? Constant.FilePath.IDCARD_PATH : Constant.FilePath.PRESCRIP_PATH, true);
        String filePath;
        if (isIdcard) {
            filePath = BitmipUtil.cropBitmap(path);
            L.i("要识别裁剪后的的图片路径==" + filePath);
            OrcIdUtil.getORCIdCard(filePath, this);
            return;
        }
        filePath = path;
        L.i("处方要压缩的图片路径==" + filePath);
        Luban.with(this)
                .load(filePath)                                   // 传人要压缩的图片列表
                .ignoreBy(60)                                  // 忽略不压缩图片的大小
                .setTargetDir(isIdcard ? Constant.FilePath.IDCARD_PATH : Constant.FilePath.PRESCRIP_PATH)                        // 设置压缩后文件存储位置
                .setRenameListener(new OnRenameListener() {
                    @Override
                    public String rename(String filePath) {
                        String mPrefix = isIdcard ? "mIDcard_" : "mPrescrip_";

                        return mPrefix + System.currentTimeMillis() + ".jpg";
                    }
                })
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        // TODO 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(final File file) {
                        // TODO 压缩成功后调用，返回压缩后的图片文件
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                L.i("tjf=图片压缩后==", path + "==" + file.getAbsolutePath());
                                upPrescriptionRv(file.getAbsolutePath());
                            }
                        });
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                        L.e("tjf=img压缩过程Throwable==", e.toString());
                        removeProgressDialog();

                    }
                }).launch();    //启动压缩
    }


    @Override
    public void onEventBusResult(MsgEventBus event) {
        super.onEventBusResult(event);
        L.i("MsgEventBus==" + event.getType());
        if (event.getType().equals(MsgEventBus.upDataInquiryorder)) {
            ShopApiHttp.get_medicine_order_details(order_id, this);
        }
    }

    List<String> urlpathList = new ArrayList<>();

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {


    }


    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
        if (requestUrl.endsWith(ShopApiHttp.get_medicine_order_details)) {
            medicineBean = GsonUtils.fromJson(requestJson.toString(), MedicineBean.class);

            setData();
            setPayTypeState();
            return;
        }

        if (requestUrl.endsWith("ocr_idcard.json")) {
            IdcardBean idcardBean = setIdCardData(requestJson.toString(), order_id, this);
            setIDcardData(idcardBean);
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.remote_update_card_info)) {
            L.i("remote_update_card_info", "身份证信息上传成功");
            removeProgressDialog();
            isIdcard = false;
            setSwitchmode();
            return;
        }
        if (requestUrl.endsWith("medicine")) {
            try {
                JSONObject data = requestJson.getJSONObject("data");

                urlpathList.add(data.getString("url"));
                L.i("medicine——imgs", prescriptioncount, urlpathList.toString());
                prescriptioncount--;
                if (prescriptioncount <= 0) {
                    ShopApiHttp.update_medicine_order_pic(order_id, urlpathList, this);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.update_medicine_order_pic)) {
            if (requestUrl.endsWith(ShopApiHttp.update_medicine_order_pic)) {
                L.i("update_medicine_order_pic", "处方图片及信息上传成功");
            }
            removeProgressDialog();
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.query_order_sult_state)) {
            try {
                JSONObject data = requestJson.getJSONObject("data");
                boolean is_repir = data.getBoolean("is_repir");
                doctor_id = data.getString("doctor_id");
                if (is_repir) {
                    mCancelTime();
                    setCanal();
                    getDoctorImg();
                    checkOrder(1);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.get_doctor_code_pic_detail)) {
            try {
                callDoctorContentLy.setVisibility(View.GONE);
                JSONObject data = requestJson.getJSONObject("data");
                String doctor_code_pic = data.getString("doctor_code_pic");
                GlideImageLoader.getInstance().loadImage(this, doctor_code_pic, call_doctor_wechat_img);

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }

        if (requestUrl.endsWith(get_pay_info)) {
            removeProgressDialog();
            FinalDbUtils.getInstance().deleteAll(CarGoodsBeans.class);
            for (MedicineBean.DataBean.OrderDetailsBean dataBean : mProductList) {
                CarGoodsBeans beans = new CarGoodsBeans();
                beans.setCount(dataBean.getQuantity());
                beans.setPrice(dataBean.getPrice());
//                beans.setProductid(dataBean.get());
                beans.setProductimg(dataBean.getProductImg());
                beans.setProductname(dataBean.getProductName());
//                beans.setMslotIndexs(new Gson().toJson(dataBean.getSlotIndexs()));
                beans.setIs_insurance(dataBean.isIs_insurance() ? 1 : 0);
                beans.setIs_remote(dataBean.isIs_remote() ? 1 : 0);
                beans.setIs_true_name(dataBean.isIs_true_name() ? 1 : 0);
                FinalDbUtils.getInstance().save(beans);
            }

            doStartActivity(ShopPayType_Aty.class, requestJson.toString());
            return;
        }

        if (requestUrl.endsWith(ShopApiHttp.query_proc_order_state)) {
            try {
                JSONObject data = requestJson.getJSONObject("data");
                int consult_state = data.getInt("consult_state");
                if (consult_state == 1) {
                    setCanal();
                    videoTopayTv.setEnabled(true);
                    videoTopayTv.setSelected(true);
                } else if (consult_state == 2) {
                    setCanal();
                    cancelOrder();
                    startActivity(ShopMain_Aty.class, null);
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {
        removeProgressDialog();

        if (requestUrl.endsWith(ShopApiHttp.get_medicine_order_details)) {

            L.i("get_medicine_order_details", errorMsg);
            showErrorLongToast("获取订单失败" + errorMsg, 4000);
            return;
        }

        if (requestUrl.endsWith("ocr_idcard.json")) {

            showErrorLongToast("识别失败，可重新拍照识别", 4000);
            return;
        }

        if (requestUrl.endsWith(ShopApiHttp.remote_update_card_info)) {
            L.i("remote_update_card_info", "身份证信息上传成功");
            return;
        }

        if (requestUrl.endsWith(ShopApiHttp.update_medicine_order_pic)) {
            L.i("update_medicine_order_pic", "处方图片及信息上传失败");
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.query_order_sult_state)) {


            return;

        }
        if (requestUrl.endsWith(ShopApiHttp.get_doctor_code_pic_detail)) {
            showErrorLongToast(errorMsg, 4000);
            return;
        }
        if (requestUrl.endsWith(get_pay_info)) {
            L.i("get_pay_info", errorMsg);
            showErrorLongToast(errorMsg, 4000);
        }
    }

    /**
     * 切换回处方拍照
     */
    public void setSwitchmode() {
        isIdcard = false;
        idcardCamareLv.removeAllViews();
        camareIdcardLayout.setVisibility(View.GONE);
        videoPrescriptionLv.addView(textureView);
    }

    /*
    有无处方布局的切换
     */
    public void setSwitcPrescriptionly(int consultation_type) {
        if (consultation_type == 0) {
            takePrescriptionLy.setVisibility(View.GONE);
            textPrescriptionLy.setVisibility(View.VISIBLE);
            setMedicationData();
        } else {
            takePrescriptionLy.setVisibility(View.VISIBLE);
            textPrescriptionLy.setVisibility(View.GONE);
        }
    }

    public void setProductData() {
        if (mCallProductAdapter == null) {
            mCallProductAdapter = new CallProductAdapter(mProductList, this);
            LinearItemDecoration divider = new LinearItemDecoration.Builder(this)
                    .setSpan(20f)
                    .setColorResource(R.color.color_white)
                    .setShowLastLine(true)
                    .build();
            callProductRv.addItemDecoration(divider);
            callProductRv.setLayoutManager(new LinearLayoutManager(this));
            callProductRv.setAdapter(mCallProductAdapter);
            callProductRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    if (mProductList.size() < 3) {//
                        return;
                    }
                    //整体的总宽度，注意是整体，包括在显示区域之外的。
                    int temp = recyclerView.computeVerticalScrollRange();
                    //计算水平滚动的距离
                    int offset = recyclerView.computeVerticalScrollOffset();
                    //计算水平滚动的范围
                    int extent = recyclerView.computeVerticalScrollExtent();
                    //计算滑动比例
                    float proportion = (float) (offset * 1.0 / (temp - extent));
                    //计算滚动条宽度
                    float transMaxRange = callMainLineRange.getHeight() - callMainLine.getHeight();
                    //设置滚动条移动
                    callMainLine.setTranslationY(transMaxRange * proportion);

                }
            });


        } else {
            if (medicineBean != null) {
                if (medicineBean.getData() != null) {
                    mProductList.clear();
                    mProductList.addAll(medicineBean.getData().getOrder_details());
                    mCallProductAdapter.notifyDataSetChanged();
                }
            }
        }

    }

    MedicationAdapter mMedicationAdapter;

    public void setMedicationData() {
        if (mMedicationAdapter == null) {
            mMedicationAdapter = new MedicationAdapter(mShopPrescriptionList, this);
            LinearItemDecoration divider = new LinearItemDecoration.Builder(this)
                    .setSpan(2f)
                    .setPadding(20f)
                    .setColorResource(R.color.sky_green_color)
                    .setShowLastLine(true)
                    .build();
            prescriptionMedicationRv.addItemDecoration(divider);
            prescriptionMedicationRv.setLayoutManager(new LinearLayoutManager(this));
            prescriptionMedicationRv.setAdapter(mMedicationAdapter);
        } else {
            if (medicineBean != null) {
                if (medicineBean.getData() != null) {
                    mShopPrescriptionList.clear();
                    mShopPrescriptionList.addAll(medicineBean.getData().getOrder_details());
                    mMedicationAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    /*
    设置基本信息
     */
    public void setData() {
        if (medicineBean != null) {
            if (medicineBean.getData() != null) {
                setProductData();
                MedicineBean.DataBean.MedicineOrderBean medicine_order = medicineBean.getData().getMedicine_order();
                patientIdcardName.setText(medicine_order.getPatient_name());
                patientIdcardSex.setText(medicine_order.getPatient_sex());
                patientIdcardPeople.setText(medicine_order.getNationality());
                patientIdcardPhone.setText(medicine_order.getPatient_phone());
                patientIdcardHeight.setText(medicine_order.getPatient_height());
                patientIdcardAge.setText(medicine_order.getAge());
                patientIdcardNumber.setText(medicine_order.getCard_no());
                prescriptionDiagnosisTv.setText(medicine_order.getDiagnosis());
                consultation_type = medicine_order.getConsultation_type();
                setSwitcPrescriptionly(consultation_type);
            }
        }
    }

    /**
     * 设置身份证信息
     *
     * @param idcardBean
     */
    public void setIDcardData(IdcardBean idcardBean) {
        patientIdcardName.setText(idcardBean.getName());
        patientIdcardSex.setText(idcardBean.getSex());
        patientIdcardPeople.setText(idcardBean.getNationality());
        patientIdcardAge.setText(idcardBean.getAge());
        patientIdcardNumber.setText(idcardBean.getNum());
    }

    public void setPayTypeState() {
        if (medicineBean != null) {
            if (medicineBean.getData() != null) {
                if (medicineBean.getData().getMedicine_order() != null) {
                    if (medicineBean.getData().getMedicine_order().getConsultation_state() == 4) {
                        videoTopayTv.setEnabled(true);
                        videoTopayTv.setSelected(true);
                    } else {
                        videoTopayTv.setEnabled(false);
                        videoTopayTv.setSelected(false);
                    }
                } else {
                    videoTopayTv.setEnabled(false);
                }
            } else {
                videoTopayTv.setEnabled(false);
            }
        } else {
            videoTopayTv.setEnabled(false);
        }
        if (videoTopayTv.isSelected()) {
            take_chufang_bt_ly.setVisibility(View.INVISIBLE);
            mPrescriptionAdapter.setIshidedel(true);
            startCountdownTimer(120, call_success_times, ShopMain_Aty.class);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        setCanal();
        mCancelTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            com.blankj.utilcode.util.FileUtils.deleteAllInDir(Constant.FilePath.PRESCRIP_PATH);
            com.blankj.utilcode.util.FileUtils.deleteAllInDir(Constant.FilePath.IDCARD_PATH);
            mCallProductAdapter = null;
            mProductList.clear();
            mPrescriptionAdapter = null;
            mPrescriptionList.clear();
            idcardCamareLv.removeAllViews();
            videoPrescriptionLv.removeAllViews();
            medicineBean = null;
            Ttys3Utils.getInstance().ledOpenOrClose(0, 1, false, 15, 15);
            Constant.isShopShipment = false;
            if (mHandler != null) {
                mHandler.removeCallbacksAndMessages(null);
                mHandler=null;
            }
        } catch (Exception e) {
            L.e("数据释放 异常  " + e.toString());
        }
    }
}
